import Vue from 'vue'
import VueRouter from 'vue-router'
/* import { store } from "@/utils/store" */

Vue.use(VueRouter)

const routes = [

  {
    path: '/',
    name: 'login',
    component: () => import('../views/element/Login-View.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/element/Register-View.vue')
  },
  {
    path: '/forget',
    name: 'forget',
    component: () => import('../views/element/Forget-View.vue')
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('../views/element/Home-View.vue')
  },
  {
    path: '/user',
    name: 'user',
    component: () => import('../views/element/User-View.vue')
  },
/*   {
    path: '/article',
    name: 'user',
    component: () => import('../views/element/Article-View.vue')
  }, */

]

const router = new VueRouter({
  routes
})


// 全局前置守卫
/* router.beforeEach((to, from, next) => {
  // 判定条件，例如检查用户是否已经登录
  if (to.name !== 'login' && !isUserLoggedIn() &&to.name !== 'register' && to.name !== 'forget') {
    // 如果用户未登录，则重定向到登录页
    next({ name: 'login' });
  } else {
    // 否则，继续当前导航
    next();
  }
});
 
function isUserLoggedIn() {
  // 检查用户是否登录的逻辑
  // 返回 true 或 false
  if(store.user.username === null || store.user.username === ''){
    return false;
  }
  else return true;
} */


router.beforeEach((to,from,next) => {
  // if(to.path === '/register' || to.path === '/login' || to.path === '/'){ //若是进入登录与注册页面 ==> pass
    if(to.path === '/register' || to.path === '/forget' || to.path === '/'){
    next()
  }else{ 
    let userToken = localStorage.getItem('token');
    console.log("Token为:"+userToken); 
    if(userToken == null || userToken == ''){
      alert("无权限，请先登录!");
      return next('/');
    }else{
      next();
    }
  }
})

export default router
